<?php

class Admin_Model_MCategory
{
    protected $connection=null;
    public function  __construct()
    {
       $this->connection=new Mongo();
    }

     /* $fiels chứa danh sách các trường muốn lấy*/
    public function getAllCategories($fiels=array())
    {

        $db=$this->connection->bookstore;
        $collection=$db->category;

        if( $fiels == null || count($fiels)==0)
            return $collection->find();
        else
        {
            $filter=array();
            for($i=0;$i<count($fiels);$i++)
            {
               $filter[$fiels[$i]]=true;
            }
            return $collection->find(array(),$filter);
        }
    }

    public function getCategoryName($idCat='0')
    {
        $db=$this->connection->bookstore;
        $collection=$db->category;

        if( $idCat == '0')
            $document = $collection->findOne();
        else
        {
            $id=new MongoId($idCat);
            $document=$collection->findOne(array("_id"=>$id));
        }

        if($document !=null)
            return $document["name"];
        else
            return "";
    }

    public function addCategory($nameCat)
    {
        $db=$this->connection->bookstore;
        $collection=$db->category;
        $cats=$collection->find();
        foreach($cats as $cat)
        {
            if(strtolower($cat["name"])==strtolower($nameCat))
                return -1;
        }
        $newCat=array("name"=>$nameCat);
        $collection->insert($newCat);
        return 1;
    }
    public function changeCategory($newName,$idCat)
    {
        $db=$this->connection->bookstore;
        $collection=$db->category;
        $cats=$collection->find();
        foreach($cats as $cat)
        {
            if($cat["name"]==$newName)
                return -1;
        }
        $id=new MongoId($idCat);
        $document=$collection->findOne(array("_id"=>$id));
        $newDocument=array("_id"=>$id,"name"=>$newName);
        $collection->update($document,$newDocument);
        return 1;
    }

    public function deleteCategory($idCat)
    {
        $db=$this->connection->bookstore;
        $collection=$db->category;
        $id=new MongoId($idCat);
        $document=array("_id"=>$id);
        return $collection->remove($document);
    }
}
?>
